'''
    广汽丰田   gqft=token=xxx;auth=xxx
'''

import datetime
import json
import os
import pprint
import random
import time
import requests
import hashlib


def get_nonce():
    """
        生成一个指定长度的随机字符串
        """
    randomlength = 16
    random_str = ''
    base_str = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    # print(random_str)
    return random_str


def genHeader(data):
    return {
        'content-type': 'application/json',
        'Authorization': data.get('auth'),
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) '
                      'Mobile/15E148 MicroMessenger/8.0.45(0x18002d2a) NetType/4G Language/zh_CN'
    }


def taskList(data, index):
    url = 'https://xcx.nevapp.gtmc.com.cn/wxapp/nev-prod/bff-nev-wxapp/point/queryTaskCenterList'
    headers = genHeader(data)
    tasks = []
    try:
        response = requests.get(url, headers=headers).json()
        taskCenterBoList = response.get("body")[0].get('taskCenterBoList')
        for task in taskCenterBoList:
            obj = {
                "title": task.get('title'),
                "taskNum": task.get('configNumber'),
                "times": task.get('times'),
                "status": task.get('completionStatus')
            }
            tasks.append(obj)
        print(f'第{index}个账号 任务:{tasks}')
    except Exception as e:
        print(f'第{index}个账号 获取任务异常 {e}')
    return tasks


def doTask(data, tasks, index):
    header = genHeader(data)
    userId = data.get('userId')
    articles = articleList(header, 1)
    sleepmoment(2)
    count = 0
    for article in articles:
        # 阅读
        if not article.get('liked') and count < 10:
            read(article, header, userId, index, count)
            sleepmoment(2)
            # 点赞
            like(tasks, article, header, userId, index, count)
            sleepmoment(2)
            # 分享
            forward(tasks, article, header, userId, index, count)
            count += 1


def read(article, header, userId, index, count):
    try:
        url = "https://xcx.nevapp.gtmc.com.cn/wxapp/nev-prod/bff-nev-wxapp/user/read"
        body = {"subjectId": article.get('id'), "subjectType": "POST", "userId": userId}
        response = requests.post(url=url, data=json.dumps(body), headers=header).json()
        # 获取积分
        url = "https://xcx.nevapp.gtmc.com.cn/wxapp/nev-prod/bff-nev-wxapp/point/grantPoints"
        body = {"ruleCode": "BROWSE_CONTENT", "businessType": "POST",
                "bsId": "BROWSE_CONTENT:102109593:" + article.get('id')}
        response = requests.post(url=url, data=json.dumps(body), headers=header).json()
        print(f'第{index}个账号 完成阅读 第{count}次 {response}')
    except Exception as e:
        print(f'第{index}个账号 阅读 第{count}次 异常 {e}')


def like(tasks, article, header, userId, index, count):
    if not isComplete('点赞', tasks):
        try:
            url = "https://xcx.nevapp.gtmc.com.cn/wxapp/nev-prod/bff-nev-wxapp/user/like"
            body = {"subjectId": article.get('id'), "subjectType": "POST", "userId": userId}
            response = requests.post(url=url, data=json.dumps(body), headers=header).json()
            print(f'第{index}个账号 完成点赞 第{count}次 {response}')
        except Exception as e:
            print(f'第{index}个账号 点赞 第{count}次 异常 {e}')


def forward(tasks, article, header, userId, index, count):
    if not isComplete('分享', tasks):
        try:
            url = "https://xcx.nevapp.gtmc.com.cn/wxapp/nev-prod/bff-nev-wxapp/user/forward"
            body = {"subjectId": article.get('id'), "subjectType": "POST", "userId": userId}
            response = requests.post(url=url, data=json.dumps(body), headers=header).json()
            # 获取积分
            url = "https://xcx.nevapp.gtmc.com.cn/wxapp/nev-prod/bff-nev-wxapp/point/grantPoints"
            body = {"ruleCode": "FORWARD_CONTENT", "businessType": "POST",
                    "bsId": "FORWARD_CONTENT:102109593:" + article.get('id')}
            response = requests.post(url=url, data=json.dumps(body), headers=header).json()
            print(f'第{index}个账号 完成分享 第{count}次 {response}')
        except Exception as e:
            print(f'第{index}个账号 分享 第{count}次 异常 {e}')


def articleList(header, pageNum):
    try:
        url = "https://xcx.nevapp.gtmc.com.cn/wxapp/nev-prod/bff-nev-wxapp/post/page"
        body = {"pageNum": pageNum, "pageSize": 30,
                "orderByField": " is_top=1 desc, sort=0, sort, top_time desc, create_time desc"}
        response = requests.post(url=url, data=json.dumps(body), headers=header).json()
        return response.get("body").get("data")
    except Exception as e:
        print(f'第{index}个账号 获取文章列表异常 {e}')
        return []


def isComplete(title, taskList):
    for task in taskList:
        if task.get('title') == title:
            return task.get('status')


def getPoint(header, index):
    try:
        url = "https://xcx.nevapp.gtmc.com.cn/wxapp/nev-prod/bff-nev-wxapp/point/pointList?pageNum=1&pageSize=1"
        response = requests.get(url=url, headers=header).json()
        print(f'{response}')
        point = response.get('body').get('data')[0]
        print(f'最后一次获取积分明细{point}')
        p = point.get('changeAfterScore')
        return f'第{index}个账号 完成任务 当前积分{p}'
    except Exception as e:
        return f'第{index}个账号 获取积分异常{e}'


def signIn(data, index):
    try:
        url = 'https://iclubh5.gtmc.com.cn/bz-signin-service/sign/signIn'
        headers = {
            'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
            'Content-Type': 'application/json;charset=utf-8',
            'X-SIX-Token': 'SIX. ' + data.get('token'),
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.42(0x18002a32) NetType/WIFI Language/zh_CN miniProgram/wxd8a42d1c0c59c15d'
        }
        data = {}
        response = requests.post(url=url, data=json.dumps(data), headers=headers).json()
        return f'第{index}个账号 签到返回: {response}'
    except Exception as e:
        return f'第{index}个账号 签到异常 {e}'


def webhook(message, webhookToken):
    url = f'http://www.pushplus.plus/send'
    headers = {
        'Content-Type': 'application/json'
    }
    data = {
        "token": webhookToken,
        "title": "广汽丰田",
        "content": message,
        "template": "json"
    }
    response = requests.post(url=url, data=json.dumps(data), headers=headers).json()
    print(f"推送成功")


def genEnvs():
    cks = os.environ['gqft']
    cks = cks.split('@')
    tokenArr = []
    for ck in cks:
        cks1 = ck.split(';')
        obj = {}
        for s in cks1:
            arr2 = s.split('=')
            obj[arr2[0]] = arr2[1]
        tokenArr.append(obj)
    return tokenArr


def sleepmoment(num):
    random_seconds = random.randint(1, num)
    print(f'休眠{random_seconds}秒')
    time.sleep(random_seconds)


if __name__ == '__main__':
    print('开始执行...')
    sleepmoment(10)
    tokenArray = genEnvs()
    length = len(tokenArray)
    print(f'读取到{length}个账号')
    webhookToken = os.environ['PUSH_PLUS_TOKEN']
    msg = ""
    for index, ck in enumerate(tokenArray):
        header = genHeader(ck)
        msg += signIn(ck, index)
        tasks = taskList(ck, index)
        doTask(ck, tasks, index)
        sleepmoment(2)
        msg += getPoint(header, index)
        sleepmoment(2)

    webhook(msg, webhookToken)
